//
//  Game.m
//  chuizijiandaobu
//
//  Created by huzhouxin on 10-11-17.
//  Super New Band Team.
//  Copyright 2010 jiandao. All rights reserved.
//

#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#import "GameViewController.h"
#import "RecordInfoViewController.h"
#import "chuizijiandaobuAppDelegate.h"
@implementation GameViewController

@synthesize shitouBtn;
@synthesize jiandaoBtn;
@synthesize buBtn;
@synthesize resetBtn;
@synthesize containerView;
@synthesize imageList;
@synthesize resultLable;
@synthesize soundPlayer;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
 if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
 // Custom initialization
 }
 return self;
 }
 */

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView {
 
 }
 */


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
	
	UIImageView *bkView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bkground.png"]];
	[self.view addSubview:bkView];
	[bkView release];
	
	//初始化视图
	UIImage *shitouImage = [UIImage imageNamed:@"shitou.png"];
	UIImage *jiandaoImage = [UIImage imageNamed:@"jiandao.png"];
	UIImage *buImage = [UIImage imageNamed:@"bu.png"];
	imageList = [NSArray arrayWithObjects:shitouImage,jiandaoImage,buImage,nil];
	[shitouImage release];
	containerView = [[UIImageView alloc] initWithFrame:CGRectMake(90, 100, 130, 130)];
	

	//containerView = [[UIImageView alloc] initWithFrame:CGRectMake(90, 100, 130, 130)];
	containerView.animationImages =imageList;
	containerView.animationDuration = 0.4;
	containerView.animationRepeatCount = 0;

	[containerView startAnimating];
	
		
	[self.view addSubview:containerView];
	
	UIButton *recordInfoBtn = [[UIButton buttonWithType:UIButtonTypeInfoDark] retain];
	recordInfoBtn.frame = CGRectMake(30, 10, 20, 20);
	[recordInfoBtn addTarget:self action:@selector(showRecordInfo) forControlEvents:UIControlEventTouchUpInside];
	
	[self.view addSubview:recordInfoBtn];
	
	
	resetBtn = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
	
	resetBtn.frame = CGRectMake(200, 5, 100, 70);
	
	[resetBtn setTitle:@"try again" forState:UIControlStateNormal];
	//UIButtonTypeCustom 按钮默认背景和字体颜色都是透明的
	[resetBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
	[resetBtn addTarget:self action:@selector(replay) forControlEvents:UIControlEventTouchUpInside];
	resetBtn.hidden = true;
	[self.view addSubview:resetBtn];
	[resetBtn release];
	
	shitouBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	shitouBtn.frame = CGRectMake(30, 280, 80, 80);
	[shitouBtn setImage:[UIImage imageNamed:@"shitou.png"] forState:UIControlStateNormal];

	shitouBtn.tag = 0;
	shitouBtn.titleLabel.text = @"石头";
	[self.view addSubview:shitouBtn];
	
	jiandaoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	[jiandaoBtn setImage:[UIImage imageNamed:@"jiandao.png"] forState:UIControlStateNormal];
	jiandaoBtn.titleLabel.text = @"jiandao";
	jiandaoBtn.frame = CGRectMake(120, 280, 80,80);
	jiandaoBtn.tag = 1;
	jiandaoBtn.titleLabel.text =@"剪刀";
	
	[self.view addSubview:jiandaoBtn];
	
	buBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	[buBtn setImage:[UIImage imageNamed:@"bu.png"] forState:UIControlStateNormal];
	buBtn.titleLabel.text =@"bu";
	buBtn.frame = CGRectMake(210, 280, 80, 80);
	buBtn.tag = 2;
	buBtn.titleLabel.text = @"布";
	[self.view addSubview:buBtn];
	
	[shitouBtn addTarget:self action:@selector(check:) forControlEvents:UIControlEventTouchUpInside];
	[jiandaoBtn addTarget:self action:@selector(check:) forControlEvents:UIControlEventTouchUpInside];
	[buBtn addTarget:self action:@selector(check:) forControlEvents:UIControlEventTouchUpInside];
	
	//当前结果显示标签
	resultLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 50, 320,40 )]; //95, 50, 180,40 
	resultLable.textAlignment = UITextAlignmentCenter;
	resultLable.textColor = [UIColor redColor];
	resultLable.hidden = true;
	resultLable.backgroundColor = [UIColor clearColor];
	[resultLable setFont:	[UIFont fontWithName:@"Helvetica-Bold" size:30]];

	[self.view addSubview:resultLable];
	[self checkRecordFile];
	
	[self initSoundResource];
	[self playSound];

	[super viewDidLoad];
	
}
//初始化声音资源
-(void)initSoundResource{
	//动画音效
	soundPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"play" ofType:@"mp3"]] error:nil];
	[soundPlayer prepareToPlay];
	
	AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"win" ofType:@"aif"]], &winSoundID);
	AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"lost" ofType:@"aif"]], &loseSoundID);
	AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"tie" ofType:@"aif"]], &tieSoundID);
	AudioServicesCreateSystemSoundID((CFURLRef)[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"pin" ofType:@"aif"]], &pinSoundID);
																
}
	 //出拳后比较结果
	 -(void)check:(id)sender{

		 //判断是否正在游戏
		 if(resultLable.hidden == false) {NSLog(@"return");return;}
		 //停止动画音效
		 [self stopPlaySound];

		 //出拳声
		 [self playPinSound];
		 [NSThread sleepForTimeInterval:0.5];
		 resetBtn.hidden = false;
		 resultLable.hidden = false;
		 
		 int user = ((UIButton *)sender).tag;
		 [containerView stopAnimating];
		 int com = rand()%3;
		 containerView.image =[imageList objectAtIndex:com];
		 NSString *currentResult = [NSString stringWithString:@""];
		 
		 if(com == user){
			 resultLable.text = @"TIE";
			 AudioServicesPlaySystemSound(tieSoundID);
			 currentResult = [NSString stringWithFormat:@"0%d%d",com,user];
		 }
		 else {
			 if(com == 0){
				 if(user == 1){
					 currentResult = [NSString stringWithFormat:@"1%d%d",com,user];
					 [self playerLose];
				 }else{
					 currentResult = [NSString stringWithFormat:@"2%d%d",com,user];
					 [self playerWin];
				 }
			 }else if(com == 1){
				 if(user == 0){
					 currentResult =  [NSString stringWithFormat:@"2%d%d",com,user];
					 [self playerWin];
				 }else{
					 currentResult =[NSString stringWithFormat:@"1%d%d",com,user];
					 [self playerLose];
				 }
			 }else if(com ==2) {
				 if(user ==0){
					 currentResult = [NSString stringWithFormat:@"1%d%d",com,user];
					 [self playerLose];
				 }else {
					 currentResult = [NSString stringWithFormat:@"2%d%d",com,user];
					 [self playerWin];
				 }
			 }
		 }
		
		 //读取记录文件,并添加新记录
		 NSMutableArray *recordArray =[[NSMutableArray alloc]initWithContentsOfFile:[GameViewController recordFile]];
		 [recordArray addObject:currentResult];
		
		 [recordArray writeToFile:[GameViewController recordFile] atomically:YES];
		 [recordArray release];

		 resultLable.hidden =false;
	 }

-(void)playerWin{
	[self playWinSound];
	resultLable.text = WIN_TITLE;
}

-(void)playerLose{
	[self playLoseSound];
	resultLable.text = LOSE_TITLE;
}
//////////////////////播放声音资源函数////////////////////
-(void)playSound{
	 
	//loops 为负数时,无限循环播放
	[soundPlayer setNumberOfLoops:-1];

	[soundPlayer play];
		
}

-(void)stopPlaySound{
	[soundPlayer pause];
}

-(void)playWinSound{
	AudioServicesPlaySystemSound(winSoundID);
}

-(void)playLoseSound{
	AudioServicesPlaySystemSound(loseSoundID);
}

-(void)playTieSound{
	AudioServicesPlaySystemSound(tieSoundID);
}

-(void)playPinSound{
	AudioServicesPlaySystemSound(pinSoundID);
}
//////////////////////////////////////////////////
	//重新开始
	 -(void)replay{
		 [self playSound];
		 resultLable.hidden = true;
		 resetBtn.hidden = true;
		 [containerView startAnimating];
				 
	 }

	//切换视图窗口
	 -(void)showRecordInfo{
		 
		 chuizijiandaobuAppDelegate *app = [[UIApplication sharedApplication]delegate];
		 
		 //显示游戏记录视图
		 [self.view removeFromSuperview];
		 [self stopPlaySound];
		 [app showRecordInfo];
	}
	
	//游戏记录文件
	+(NSString *)recordFile{
		NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask, YES);
		NSString *documentsDirectoryPath = [paths objectAtIndex:0];
		NSString *path = [documentsDirectoryPath stringByAppendingPathComponent:@"record.plist"];
		NSLog(@"%@",path);
		return path;
	}
//检查是否存在游戏记录文件,没有则生成文件
-(void)checkRecordFile{
	NSString *path = [GameViewController recordFile];

	NSFileManager *fileManger = [NSFileManager defaultManager];
	if (![fileManger fileExistsAtPath:path] ){
		//初始化新文件
		NSMutableArray *recordArray= [[NSMutableArray alloc]init];
		[recordArray addObject:@"000"];
		[recordArray writeToFile:path atomically:YES];
		[recordArray release];
	}
}


	/*
	 // Override to allow orientations other than the default portrait orientation.
	 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	 // Return YES for supported orientations
	 return (interfaceOrientation == UIInterfaceOrientationPortrait);
	 }
	 */
	 
	 - (void)didReceiveMemoryWarning {
		 // Releases the view if it doesn't have a superview.
		 [super didReceiveMemoryWarning];
		 
		 // Release any cached data, images, etc that aren't in use.
	 }
	 
	 - (void)viewDidUnload {
		 [super viewDidUnload];
		 // Release any retained subviews of the main view.
		 // e.g. self.myOutlet = nil;
	 }
	 
	 
	 - (void)dealloc {
		 [containerView release];
		 [shitouBtn release];
		 [jiandaoBtn release];
		 [buBtn release];
		 
		 [resultLable release];
		 if(soundPlayer !=nil){
			 if([soundPlayer isPlaying] == YES)
				 [soundPlayer stop];
			 [soundPlayer release];
		 }
		 
		 [super dealloc];
	 }
	 
	 
	 @end
